import requests
import os
from pathlib import Path
from argparse import ArgumentParser


class FlutterL10nSync:
    def __init__(self, output_dir=None):
        self.base_url = "https://www.runmefit.cn/api/translates/arb/lang"
        self.mapping = self.get_language_mapping()
        self.output_dir = Path(output_dir) if output_dir else Path("lib/l10n")
        self.output_dir.mkdir(parents=True, exist_ok=True)

    def get_language_mapping(self):
        return {
            'ar': 'ar',
            'de-DE': 'de',
            'en': 'en',
            'es-AR': 'es',
            'es-ES': 'es',
            'fr': 'fr',
            'iw': ['iw', 'he'],
            'hi-IN': 'hi_IN',
            'in': ['id'],
            'it-IT': 'it',
            'ja': 'ja',
            'ko': 'ko',
            'nl-NL': 'nl',
            'pl-PL': 'pl',
            'pt-PT': 'pt',
            'ms': 'ms',
            'ro': 'ro',
            'ru-RU': 'ru',
            'th': 'th',
            'tr': 'tr',
            'vi': 'vi',
            'zh-CN': 'zh_CN',
            'zh-Hant': 'zh_HK',
            'zh-HK': 'zh_HK',
            'zh-TW': 'zh_HK',
            'mn': 'mn',
            'sk': 'sk',
            'cs': 'cs',
            'hu': 'hu'
        }

    def download_language(self, lang_code):
        url = f"{self.base_url}/{lang_code}/group_id/1"
        try:
            response = requests.get(url, timeout=10)
            response.raise_for_status()
            return response.text
        except Exception as e:
            print(f"下载失败 {lang_code}: {str(e)}")
            return None

    def process_language(self, lang_code, target_codes):
        content = self.download_language(lang_code)
        if not content:
            return

        original_locale = lang_code.replace('-', '_')
        if type(target_codes) == list:
            print("{}是数组".format(original_locale))
            for target_code in target_codes:
                modified_content = content.replace(
                    f'"@@locale":"{original_locale}"',
                    f'"@@locale":"{target_code}"'
                )
                self.save_file(target_code, modified_content)
        else:
            print("{}不是数组".format(original_locale))
            self.save_file(original_locale, content)

    def save_file(self, lang_code, content):
        filename = self.output_dir / f"intl_{lang_code}.arb"
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"成功生成: {filename}")
        except Exception as e:
            print(f"文件保存失败 {lang_code}: {str(e)}")

    def run(self):
        print("开始同步多语言文件...")
        for lang_code, target_codes in self.mapping.items():
            self.process_language(lang_code, target_codes)
        print("同步完成")


if __name__ == "__main__":
    parser = ArgumentParser(description="Flutter多语言文件同步工具")
    parser.add_argument('--output', '-o', help="输出目录路径 (默认: lib/l10n)")

    args = parser.parse_args()

    syncer = FlutterL10nSync(args.output)
    syncer.run() 